package com.opal.config.shiro;

import com.opal.system.entity.table.OpalPermission;
import com.opal.system.entity.table.OpalPermissionExample;
import com.opal.system.mapper.mysql.OpalPermissionMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ShiroPermissionFactory {

    @Resource
    private OpalPermissionMapper opalPermissionMapper;

//    /** 记录配置中的过滤链 */
//    public static String definition = "";

//    /**
//     * 初始化设置过滤链
//     */
//    @Override
//    public void setFilterChainDefinitions(String definitions) {
//        System.out.println("进来了？？？？？进来了？？？？？进来了？？？？？进来了？？？？？进来了？？？？？进来了？？？？？进来了？？？？？");
//        definition = definitions;// 记录配置的静态过滤链
//        //需要授权的配置
//        Map<String, String> otherChains = new HashMap<String, String>();
//        List<OpalPermission> opalPermissions = opalPermissionMapper.selectByExample(new OpalPermissionExample());
//        for (OpalPermission op:opalPermissions ){
//            String urlPath = op.getPermissionUrl();
//            String permissionCode = op.getPermissionCode();
//            //设置需要权限的路径：key：路径(不能为空)，value：权限名称
//            if(!StringUtils.isBlank(urlPath)){
//                otherChains.put(urlPath,permissionCode);
//            }else {
//                System.out.println("启动失败：urlPath为空或null");
//            }
//
//        }
//
//        otherChains.put("/**", "authc");
//        // 加载配置默认的过滤链
//        Ini ini = new Ini();
//        ini.load(definitions);
//        //did they explicitly state a 'urls' section?  Not necessary, but just in case:
//        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
//        if (CollectionUtils.isEmpty(section)) {
//            //no urls section.  Since this _is_ a urls chain definition property, just assume the
//            //default section contains only the definitions:
//            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
//        }
//        setFilterChainDefinitionMap(section);
//
//        // 加上数据库中过滤链
//        section.putAll(otherChains);
//        setFilterChainDefinitionMap(section);
//    }

    public void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean) {
        synchronized (this) {
            AbstractShiroFilter shiroFilter;
            try {
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
            } catch (Exception e) {
                throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
            }
            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();

            // 清空拦截管理器中的存储
            manager.getFilterChains().clear();
            // 清空拦截工厂中的存储,如果不清空这里,还会把之前的带进去
            //            ps:如果仅仅是更新的话,可以根据这里的 map 遍历数据修改,重新整理好权限再一起添加
            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
            // 动态查询数据库中所有权限
            //需要授权的配置
            Map<String, String> otherChains = new HashMap<String, String>();
            List<OpalPermission> opalPermissions = opalPermissionMapper.selectByExample(new OpalPermissionExample());
            for (OpalPermission op:opalPermissions ){
                String urlPath = op.getPermissionUrl();
                String permissionCode = op.getPermissionCode();
                //设置需要权限的路径：key：路径(不能为空)，value：权限名称
                if(!StringUtils.isBlank(urlPath)){
                    otherChains.put(urlPath,"perms["+permissionCode+"]");
                }else {
                    System.out.println("启动失败：urlPath为空或null");
                }

            }
            shiroFilterFactoryBean.setFilterChainDefinitionMap(otherChains);
            // 重新构建生成拦截
            Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
            for (Map.Entry<String, String> entry : chains.entrySet()) {
                manager.createChain(entry.getKey(), entry.getValue());
            }
            System.out.println("--------------- 动态生成url权限成功！ ---------------");

            // 动态更新该角色相关联的用户shiro权限
//            if(roleId != null){
//                updatePermissionByRoleId(roleId,isRemoveSession);
//            }
        }
    }


}
